// -----------------------------------------------------------------------
//  <copyright file="StartupLogger.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2022 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://www.dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2022-11-16 20:58</last-date>
// -----------------------------------------------------------------------

namespace DaprPlus.Logging;

/// <summary>
/// 系统启动日志
/// </summary>
public class StartupLogger
{
    public IList<StartupLogInfo> LogInfos { get; } = new List<StartupLogInfo>();

    public void LogInformation(string message, string logName)
    {
        Log(LogLevel.Information, message, logName);
    }

    public void LogDebug(string message, string logName)
    {
        Log(LogLevel.Debug, message, logName);
    }

    public void Log(LogLevel logLevel, string message, string logName, Exception? exception = null)
    {
        var log = new StartupLogInfo
        {
            LogLevel = logLevel,
            Message = message,
            LogName = logName,
            Exception = exception,
            CreatedTime = DateTime.Now
        };
        LogInfos.Add(log);
    }

    public void Output(IServiceProvider provider)
    {
        IDictionary<string, ILogger> dict = new Dictionary<string, ILogger>();
        foreach (var info in LogInfos.OrderBy(m => m.CreatedTime))
        {
            if (!dict.TryGetValue(info.LogName, out var logger))
            {
                logger = provider.GetLogger(info.LogName);
                dict[info.LogName] = logger;
            }
            logger.Log(info.LogLevel, info.Exception, info.Message);
        }

        LogInfos.Clear();
    }

    public class StartupLogInfo
    {
        public LogLevel LogLevel { get; set; }

        public string? Message { get; set; }

        public Exception? Exception { get; set; }

        public string LogName { get; set; } = typeof(StartupLogger).FullName!;

        public DateTime CreatedTime { get; set; }
    }
}
